// 持久化方法

import { app } from 'electron'
import { LocalStorage } from 'node-localstorage'
import { is } from '@electron-toolkit/utils'
import { dirname } from 'path'
import dayjs from 'dayjs'
import isSameOrBefore from 'dayjs/plugin/isSameOrBefore'

export interface Count {
  count: number
  max: number
}

export interface Config {
  color: string
  opacity: number
  max: number
  step: number
  autoOpen: boolean
}

let appUrl = ''
if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
  appUrl = '.'
} else {
  // 这种写法是为了防止在打包后，路径错误，但是在开机自动启动的情况下，路径是错误的
  // appUrl = process.cwd()
  // app.getPath('exe') 获取的是exe文件的路径
  // 之所以采用这种方式，就是为了防止出现因开机自启动，导致的获取路径错误的情况
  appUrl = dirname(app.getPath('exe'))
}

export const storageInfo = (key: string, count: Count) => {
  const localStorage = new LocalStorage(appUrl + '/scratch/info')
  const infoStr = localStorage.getItem("info")
  if (infoStr != null && infoStr != 'undefined') {
    let info = JSON.parse(infoStr)
    info[key] = count
    localStorage.setItem("info", JSON.stringify(info))
  } else {
    let info = {
      [key]: count
    }
    localStorage.setItem("info", JSON.stringify(info))
  }
}

export const storageConfig = (config: Config) => {
  if (config) {
    const configStorage = new LocalStorage(appUrl + '/scratch/config')
    configStorage.setItem('config', JSON.stringify(config))
    setAutoOpenStatus(config)
  }
}

export const setAutoOpenStatus = (config?: Config) => {
  if (!config) {
    const configStorage = new LocalStorage(appUrl + '/scratch/config')
    const configStr = configStorage.getItem('config')
    if (configStr != null && configStr != 'undefined') {
      config = JSON.parse(configStr)
    }
  }
  if (app.isPackaged) {
    if (config && config.autoOpen) {
      // 开机启动
      // console.log('开机启动')
      app.setLoginItemSettings({
        openAtLogin: true
      })
    } else {
      // 关闭开机启动
      // console.log('关闭开机启动')
      app.setLoginItemSettings({
        openAtLogin: false
      })
    }
  }
}

export const getPosition = (winPositionTag: String) => {
  const localStorage = new LocalStorage(appUrl + '/scratch/position')
  const str = localStorage.getItem(winPositionTag)
  if (str != null && str != 'undefined') {
    return JSON.parse(str)
  }
}

export const setPostion = (winPositionTag: String, position: String) => {
  const localStorage = new LocalStorage(appUrl + '/scratch/position')
  localStorage.setItem(winPositionTag, position)
}

export const getInfoList = (startDate: Date, endDate: Date) => {
  const localStorage = new LocalStorage(appUrl + '/scratch/info')
  const infoStr = localStorage.getItem("info")
  if (infoStr != null && infoStr != 'undefined') {
    let info = JSON.parse(infoStr)
    let infoList:{name: string, info: Count}[] = []
    dayjs.extend(isSameOrBefore)
    let start = dayjs(startDate)
    let max = 0
    do {
      const dateStr = start.format('YYYY-MM-DD')
      // 列表新增
      const dayInfo:Count = info[dateStr]
      if(dayInfo) {
        infoList.push({
          name: dateStr,
          info: dayInfo
        })
        max = dayInfo.max
      } else {
        // 没有缓存时增加默认值
        infoList.push({
          name: dateStr,
          info: {
            count: 0,
            max
          }
        })
      }
      start = start.add(1, 'day')
    } while (start.isSameOrBefore(endDate, 'day'))
    return infoList.reverse()
  } else {
    return []
  }
}
